package com.damuzee.common.freemarker.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import com.damuzee.common.freemarker.TemplateManager;
import com.damuzee.common.web.spring.MessageResolver;
import com.damuzee.core.web.WebContext;
import com.damuzee.core.web.springmvc.RichFreeMarkerView;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Component
public class TemplateManagerImpl implements TemplateManager {

	private static final String SYSTEM_RESOURCE_PATH = "system.resource.path";

	private static final String HTML_STATIC_PATH = "html.static.path";

	private FreeMarkerConfig freemarkarCfg = null;



	public String createHtml(HttpServletRequest request, String templatePath,
			String templateName, Map<String, Object> data) {

		String htmlRealPath = getHtmlPath( WebContext.getRealPath(request) + MessageResolver.getMessage(request, HTML_STATIC_PATH),
				templateName);

		String contextPath = WebContext.getContextPath(request);
		data.put(RichFreeMarkerView.CONTEXT_PATH, contextPath);
		data.put(
				RichFreeMarkerView.SOURCE_PATH,
				contextPath + MessageResolver.getMessage(request, SYSTEM_RESOURCE_PATH));


		Configuration freemarkerCfg = freemarkarCfg.getConfiguration();
		// 加载模版
		freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");

		try {
			// 指定模版路径
			Template template = freemarkarCfg.getConfiguration().getTemplate( templatePath);
			template.setEncoding("UTF-8");

			// 静态页面路径
			File htmlFile = new File(htmlRealPath);
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
			// 处理模版
			template.process(data, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return htmlRealPath;
	}

	public String getHtmlPath(  String path, String fileName) {

		String htmlPath = path + "/";
		File htmlFile = new File(htmlPath);
		if (!htmlFile.exists()) {
			htmlFile.mkdirs();
		}
		htmlPath = htmlPath + "/" + fileName + ".html";
		return htmlPath;
	}

	public FreeMarkerConfig getFreemarkarCfg() {
		return freemarkarCfg;
	}

	public void setFreemarkarCfg(FreeMarkerConfig freemarkarCfg) {
		this.freemarkarCfg = freemarkarCfg;
	}

}
